package com.cppddd.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

import com.cppddd.util.SinaWeiboUtil;

public class SystemFilter implements Filter {
	protected String encoding = null;   

    protected FilterConfig filterConfig = null; 

    protected boolean ignore = true;   
    
    @Override
    public void destroy() {
        this.encoding = null;    
        this.filterConfig = null; 
    }

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		System.out.println(((HttpServletRequest)request).getRequestURI());		
		if(((HttpServletRequest)request).getSession().getAttribute("token") == null){
			
			
			//未登录
			//rsp.sendRedirect(new SinaWeiboUtil().getLoginUrl());
			JSONObject jsonObject = new JSONObject();
			PrintWriter pw = response.getWriter();				
			//需要登录
			try {				
				String login_url = new SinaWeiboUtil().getLoginUrl();
				jsonObject.put("success", "1");//未登录
				jsonObject.put("login_url", login_url);//登陆地址
				pw.write(jsonObject.toString());
				pw.close();				
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			chain.doFilter(request, response);
		}
		
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
//		// TODO Auto-generated method stub
//		this.filterConfig = filterConfig;  
//		this.encoding = filterConfig.getInitParameter("encoding");   
//		String value = filterConfig.getInitParameter("ignore");   
//        if (value == null)   
//            this.ignore = true;   
//        else if (value.equalsIgnoreCase("true"))   
//            this.ignore = true;   
//        else if (value.equalsIgnoreCase("yes"))    
//            this.ignore = true;    
//        else   
//            this.ignore = false;    

	}
	
	protected String selectEncoding(ServletRequest request) {    
		   
        return (this.encoding);    
   
    }

}
